package com.example.pubmedcrawler.controller;

import com.example.pubmedcrawler.model.SearchResult;
import com.example.pubmedcrawler.service.PubMedCrawlerService;
// import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
// import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;


@Controller
public class LiteratureController {

    private final PubMedCrawlerService crawlerService;

    // @Autowired  // 通过构造器注入
    public LiteratureController(PubMedCrawlerService crawlerService) {
        this.crawlerService = crawlerService;
    }

    @GetMapping("/")
    public String showSearchForm() {
        return "search";
    }

    @GetMapping("/search")
    public String searchLiterature(@RequestParam(defaultValue = "") String query,
                                   @RequestParam(defaultValue = "1") int page,
                                   Model model) {
        try {
            SearchResult result = crawlerService.search(query, page);
            model.addAttribute("literatures", result.getLiteratures());
            model.addAttribute("query", query);
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", result.getTotalPages());
            return "results";
        } catch (IOException e) {
            model.addAttribute("error", "获取文献失败: " + e.getMessage());
            return "search";
        }
    }
}